package com.summer.study.leetcode.algorithm;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther: 杨杰
 * @date: 2019/7/25 15:56
 * @description: 两数之和
 * https://leetcode-cn.com/problems/two-sum/
 */
public class Test_001 {

    /**
     * @param nums :
     * @param target :
     * @auther:   杨杰
     * @date:     2019/7/25 16:12
     * @description 方法1 暴力法
     */
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[] {i,j};
                }
            }
        }
        throw new IllegalArgumentException("查找不到");
    }

    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw new IllegalArgumentException("查找不到");
    }


    public static int[] twoSum3(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("查找不到");
    }


    public static void main(String[] args) {
        int[] nums={1,5,6,7,8};
        int[] result=twoSum(nums,28);
        Arrays.stream(result).forEach(value -> System.out.println(value));
    }

}
